<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.lang.Object" %> 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WELCOME TO FILE MANAGER!!!</title>
</head>
<body>
<%! boolean success = true; %>
<% 
// the directory where the uploaded file will be saved. 
String savePath = new String(request.getParameter("dir").getBytes("ISO-8859-1"), "UTF8"); 
String filename = ""; 

ServletInputStream in = request.getInputStream(); 
int BUFSIZE = 4096;
byte[] line = new byte[BUFSIZE]; 
int i = in.readLine(line, 0, line.length); 
int boundaryLength = i - 2; 
String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character 

while (i != -1) 
{
  String newLine = new String(line, 0, i, "UTF-8"); 
  if (newLine.startsWith("Content-Disposition: form-data; name=\"")) 
  {
	String s = new String(line, 0, i - 2, "UTF-8"); 
    int pos = s.indexOf("filename=\""); 
    if (pos != -1) 
    {
      String filepath = s.substring(pos+10, s.length()-1); 
      // Windows browsers include the full path on the client 
      // But Linux/Unix and Mac browsers only send the filename 
      // test if this is from a Windows browser 
      pos = filepath.lastIndexOf("\\"); 
      if (pos != -1) 
        filename = filepath.substring(pos + 1); 
      else 
        filename = filepath; 
    } 

    //this is the file content 
    i = in.readLine(line, 0, 128); 
    i = in.readLine(line, 0, 128); 
    // blank line   
    i = in.readLine(line, 0, 128); 

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
    newLine = new String(line, 0, i, "UTF-8"); 

    while (i != -1 && !newLine.startsWith(boundary)) 
    {
      // the problem is the last line of the file content 
      // contains the new line character. 
      // So, we need to check if the current line is 
      // the last line. 
      buffer.write(line, 0, i); 
      i = in.readLine(line, 0, 128); 
      newLine = new String(line, 0, i); 
    } 
    try 
    {
      // save the uploaded file 
      FileOutputStream f = new FileOutputStream(new File(savePath, filename));
      byte[] bytes = buffer.toByteArray(); 
      f.write(bytes, 0, bytes.length - 2); 
      f.close(); 
    } 
    catch (Exception e) 
    {
    	success = false;
    } 
  } 
  i = in.readLine(line, 0, line.length); 

} // end while 

	if (success)
		out.println("SUCCESSFUL DOWNLOAD");
	else
		out.println("not successful download");
%>

<br>
<a href = "main.jsp">back to manager</a>
</body>
</html>
